/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */


$(function() {
    var currRoom = "Veg";
    var event;
    
    $("#room").change(function() {
        event.removeEventListener(currRoom, newMessage);
        currRoom = $(this).val();
        event.addEventListener(currRoom, newMessage)
    });
    
    $("#send").on("click", function() {
        var msg = $("#message").val();
        if (!msg)
            return;

        $.post("chat", {
            "message": msg,
            "roomName": currRoom
        }).done(function(data) {
            console.log("success");
            $("#message").val("");
        }).fail(function(data) {
            console.log("fail");
        });

    });

    event = new EventSource("chatroom");
    event.addEventListener(currRoom, newMessage);
});

function newMessage(result) {
    var allChats = $("#chats").val();
    var d = JSON.parse(result.data);
    $("#chats").val(allChats + "\n" + d.text);
}



function checkUser()
{
    
    var promise =  $.getJSON("chatFunc");
    promise.done(function(data){
        if(data.username === "Admin")
        {
           $("#send").css({ display: "inline" });
           $("#message").css({ display: "inline" });
        }
        else
        {
             $("#send").css({ display: "none" });
             $("#message").css({ display: "none" });
             
        }
       
   }).fail(function(){
       window.location.assign("login2.html");
   });
}
